package com.palm.core.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;
import org.noear.solon.Solon;
import org.noear.solon.core.util.PrintUtil;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * 通过html导出Pdf
 * 若使用该功能，需先添加依赖
 *  <dependency>
 *    <groupId>org.xhtmlrenderer</groupId>
 *    <artifactId>flying-saucer-pdf-itext5</artifactId>
 *  </dependency>
 */
public class PdfExportUtil {
    /**
     * 通过enjoy模板导出
     *
     * @param templatePath
     * @param params
     * @param out
     */
    public static void export(String templatePath, Map<String, Object> params, OutputStream out) {
        Engine engine = Engine.createIfAbsent("template", e -> {
            if (Solon.global().cfg().isDebugMode()) {
                e.setDevMode(true);
            }
            e.setBaseTemplatePath("template");
            e.setToClassPathSourceFactory();
        });
        Template template = engine.getTemplate(templatePath);
        String outStr = template.renderToString(params);
        export(outStr, out);
    }

    /**
     * 通过html导出pdf,中文字体注意使用Microsoft YaHei或SimSun字体
     *
     * @param htmlStr
     * @param os
     */
    public static void export(String htmlStr, OutputStream os) {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlStr);
        ITextFontResolver fontResolver = renderer.getFontResolver();
        boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
        try {
            if (new File("fonts", "simsun.ttc").exists()) {
                fontResolver.addFont("fonts" + File.separator + "simsun.ttc", BaseFont.IDENTITY_H, !isWindows);
            } else {
                PrintUtil.warn("没有发现SimSun字体，如有需要，请将字体问下放在当前目录的fonts目录下，文件名为simsun.ttc");
            }
            if (new File("fonts", "msyh.ttf").exists()) {
                fontResolver.addFont("fonts" + File.separator + "msyh.ttf", BaseFont.IDENTITY_H, !isWindows);
            } else {
                PrintUtil.warn("没有发现Microsoft YaHei字体，如有需要，请将字体问下放在当前目录的fonts目录下，文件名为msyh.ttf");
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        renderer.layout();
        try {
            renderer.createPDF(os, true);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
